const blogmodel = require('../model/blog.js')
const tagmodel = require('../model/tag.js')
const Blog = require('../schema/blog.js').Blog;
const path=require('path')
const usermodel = require('../model/user.js')
const { uploadFile } = require('../util/upload')
const moment = require('moment');
moment.locale('zh-cn');



const wx = async (ctx) => {
    
    await ctx.render('wx',{
        "active": "管理发布" || '',
        "login": ctx.session.login == "1" ? true : false,
        "username": ctx.session.login == "1" ? ctx.session.username : "",
        "avatar": "/album/" + ctx.session.avatar || '',
        "title": "内容发布",
    })
}
const oauth = async (ctx) => {
    
    await ctx.render('oauth',{
        "active": "管理发布" || '',
        "login": ctx.session.login == "1" ? true : false,
        "username": ctx.session.login == "1" ? ctx.session.username : "",
        "avatar": "/album/" + ctx.session.avatar || '',
        "title": "内容发布",
    })
}


const send = async (ctx) => {
    if (ctx.session.login != "1") {
        ctx.body = "非法闯入，这个页面要求登陆！";
        return;
    }
		var bid,data,doc
		if(ctx.query.bid){
			bid = ctx.query.bid;
			 data = { "hrefid": bid }
			 doc = await blogmodel.findOne(data)
			 await ctx.render('send', {
			 	"editcont":doc.content || '',
			 	"edittit":doc.title || '',
			 	"fmpath":doc.fmpath || '',
			 		"active": "管理发布" || '',
			 		"login": ctx.session.login == "1" ? true : false,
			 		"username": ctx.session.login == "1" ? ctx.session.username : "",
			 		"avatar": "/album/" + ctx.session.avatar || '',
			 		"title": "内容发布",
			 		"keywords":"顶上前端,ariza全栈,",
			 		"description":"追求源于热爱，ariza全栈开发，你指间跃动的闪光，是我一生不变的信仰",
			 })
		}else{
			await ctx.render('send', {
			"editcont": '',
			"edittit": '',
			"fmpath": '',
				"active": "管理发布" || '',
				"login": ctx.session.login == "1" ? true : false,
				"username": ctx.session.login == "1" ? ctx.session.username : "",
				"avatar": "/album/" + ctx.session.avatar || '',
				"title": "内容发布",
				"keywords":"顶上前端,ariza全栈,",
				"description":"追求源于热爱，ariza全栈开发，你指间跃动的闪光，是我一生不变的信仰",
			})
		}
		

		
    
}
const sendcont = async (ctx) => {
    var count = await Blog.count({}, function (err, res) {
     
        return res
    })
		
		if(ctx.request.body.id!=''){
			
			
			let pull = {
			
				title: ctx.request.body.title,
				content: ctx.request.body.content,
				fmpath: ctx.request.body.fmpath,
			}
			
			let hrefid = {"hrefid":ctx.request.body.id}

				await blogmodel.doedit(hrefid, pull)
			
			ctx.body = "1"
		}else{
			let blog = {
					username: ctx.session.username,
					title: ctx.request.body.title,
					content: ctx.request.body.content,
					fmpath: ctx.request.body.fmpath,
					stars:1,
					datetime: moment().format('LL'),
					hrefid: count,
			}
			await blogmodel.insertone(blog)
			ctx.body = "1"
		}


   
}


const getuserinfo = async (ctx) => {
    //这个页面接收一个参数，页面
    var username = ctx.query.username;
    var data = { "username": username }
    let doc = await usermodel.findalluser(data)
    ctx.body = {
        res: doc,
    };
}
const page = async (ctx) => {
    await Blog.count({}, function (err, res) {
        ctx.body = res
    })

}



const blogart = async (ctx) => {
    var page = ctx.query.bid;
    var data = { "hrefid": page }
    let doc = await blogmodel.findOne(data)
	let newstars=doc.stars
	let taglist = await tagmodel.findnormal({})
	console.log(newstars)
    let all={}
    let doc2 = await blogmodel.findnormal(all,5)
    
   let pull = {
    "stars": newstars+1,
    
  }
    await blogmodel.doedit(data, pull)
 
    await ctx.render('article', {
        "alllist":doc2,
        "title": doc.title,
        "stars": doc.stars,
        "taglist":taglist,
        "keywords":doc.title+"_顶上前端,ariza全栈,",
        "description":doc.title+"_追求源于热爱，ariza全栈开发，你指间跃动的闪光，是我一生不变的信仰",
        "content": doc.content,
        "username": doc.username,
        "loginuser": ctx.session.username,
        "comment": doc.comment,
        'hrefid': doc.hrefid,
        "datetime": doc.datetime,
        "login": ctx.session.login == "1" ? true : false
    })

}

const comment = async (ctx) => {
  
    let hrefid = {"hrefid":ctx.request.body.hrefid}
        
   
    let userid = ctx.request.body.username
    let comment = ctx.request.body.comment


    let newdata = {
        $push: {
            "comment": {
                "usercomment": userid,
                "commented": comment,
                "avatar": ctx.session.avatar,
            }
        }
    }
    await blogmodel.doedit(hrefid, newdata)
    ctx.body = '评论成功'
    ctx.redirect(ctx.request.body.nowurl)
}

const delblog = async (ctx) => {
  
  
 
    let hrefid = {"_id":ctx.request.body.id}
        
    await blogmodel.dellist(hrefid)
    
    var pageNum = ctx.request.body.pageNum || 1;
	const reg = new RegExp(ctx.request.body.searchValue, 'i')
	let data 
	if(ctx.request.body.searchValue==''){
		data={}
	}else{
		data = {
	    $or: [
	      { title: { $regex: reg } }
	    ]
	  }
	}
	var pageSize = Number(ctx.request.body.pageSize)
	var skipnum = Number((pageNum - 1) * pageSize)
	var sort = {
		"datetime": -1
	}
	let doc = await blogmodel.findall(data, skipnum, pageSize, sort)
    
    
    
    ctx.body = {
    	status:200,
    	data:doc
    }
   
}





const sendfm = async (ctx) => {
 
    // 上传文件请求处理
    let result = { success: false }
    let serverFilePath = path.join(__dirname, '../public')
    // 上传文件事件
    result = await uploadFile(ctx, {
        fileType: 'blogfm',
        path: serverFilePath
    })

    ctx.body={
       "path": result.data.pictureUrl
    }
}



module.exports = {
    send,
    sendcont,
delblog,
    getuserinfo,
    page,
    blogart,
    comment,
    sendfm,
    oauth,
    wx
}